Categories
Node.js Tips

Node.js Tips — POST Requests, Express Route Params, S3 Data, and More

Spread the love

Like any kind of apps, there are difficult issues to solve when we write Node apps. In this article, we’ll look at some solutions to common problems when writing Node apps.

Get the Browser Language in Express

To get the browser language in an Express app, we can use the req.headers['accept-language'] property to get the accept-language header.

Then request.acceptsLanguages method also gets the accepted language header.

For instance, we can write:

const express = require('express');
app.get('/translation', (req, res) => {
  const lang = req.acceptsLanguages('fr', 'es', 'en');
  if (lang) {
    console.log(lang);
  }
  else {
    console.log('None of [fr, es, en] is accepted');
  }
  //...
});

acceptsLanguages makes a list of languages that the app can accept.

If one of the values are in the Accepts-Language header, then it returns true ,

Otherwise, it returns false .

There’s also the accepts module that does the same thing.

To install it, we run:

npm install accepts

Then we can use it by writing:

const accepts = require('accepts');
const http = require('http');

const app = (req, res) => {
  const accept = accepts(req);
  switch (accept.type(['json', 'html'])) {
    case 'json':
      res.setHeader('Content-Type', 'application/json');
      res.write(JSON.stringify({ hello: 'world' ));
      break;
    case 'html':
      res.setHeader('Content-Type', 'text/html');
      res.write('<b>hello, world</b>');
      break;
    default:
      res.setHeader('Content-Type', 'text/plain');
      res.write('hello, world');
      break;
  }
  res.end()
}

http.createServer(app).listen(3000)

We use the accept module to check the Accept header. We can check the kind of language that it requests in the Accept header. It has the languages method to get the browser language from the Accepts-Language header.

How to Construct HTTP POST Request with Form Params

We can construct an HTTP POST request with form parameters with the querystring module.

To install it, we run:

npm i querystring

Then we can write:

const querystring = require('querystring');

axios.post(
  '/login',
  querystring.stringify({
    username: 'abcd',
    password: '12345',
  }),
  {
    headers: {
      "Content-Type": "application/x-www-form-urlencoded"
    }
  }
)
.then((response) => {
  console.log(response);
});

We called the querystring.stringify method to construct a query string with the username and password keys. Also, we set the headers with the Content-Type header set to “application/x-www-form-urlencoded” . This way, we send the query string as form data.

How to Configure Dynamic Routes with Express.js

We can configure dynamic routes with Express by allowing parameters.

For instance, we can write:

app.get('/article/:name', (req, res) => {
  res.render(req.params.name);
});

We can also restrict the allowed values of id by writing:

app.get('/article/:name(article|article2|article3)', (req, res) => {
  const name = req.params.name;
  res.render(name);
});

We restrict the name parameter to be one of article1 , article2 ,or article3 .

In both examples, we get the parameter value by using the req.params.name property.

req.params has the value of name .

Catch Express body-parser Error

We can create our own middleware to catch errors raised by body-parser .

For instance, we can write:

app.use((error, req, res, next) => {
  if (error instanceof SyntaxError) {
    sendError(res, 'error');
  } else {
    next();
  }
});

We check if a SyntaxError is raised by using error instanceof SyntaxError. If it is, then we call sendError to process the error. Otherwise, we call next to call the next middleware in the chain.

Return Hostname with Node.js

We can use the os module’s hostname method to return the hostname.

For instance, we can write:

const os = require("os");
const hostname = os.hostname();

to do that.

Listing Objects from AWS S3 in a Node App

We can get items stored in S3 with the aws-sdk package.

For instance, we can write:

const AWS = require('aws-sdk');
AWS.config.update({
  accessKeyId: 'key',
  secretAccessKey: 'secret',
  region: 'region'
});

const s3 = new AWS.S3();

const params = {
  Bucket: 'bucket',
  Delimiter: '/',
  Prefix: '/path/prefix'
}

s3.listObjects(params, (err, data) => {
  if (err){
    return console.log(err);
  }
  console.log(data);
});

We authenticate with AWS. Then we get the bucket with the Bucket property.

Delimiter is the path separator.

Prefix is the prefix for the path and bucket data.

Then we call listObjects with the path.

The callback’s data parameter has the bucket data.

Conclusion

If it’s not created when we join it, then it’ll be created. We can get data from S3. Express routes can be made dynamic with parameters. We can send form data as a query with a POST request with Axios

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *